package com.kb.erp.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.erp.controller.DDYXxlJobController;
import com.kb.erp.entity.pcbout.*;
import com.kb.erp.entity.quote.BaseResult;
import com.kb.erp.mapper.pg.*;
import com.kb.erp.mapper.sqlServer.PCBOutMapper;
import com.kb.erp.service.MaterialService;
import com.kb.erp.util.MessageUtil;
import com.kb.erp.vo.ExportVO;
import kingdee.bos.webapi.client.K3CloudApiClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@DS("pg-material")
@Slf4j
public class MaterialServiceImpl implements MaterialService {
    private static Logger logger = LoggerFactory.getLogger(DDYXxlJobController.class);
    @Resource
    private StockMapper stockMapper;

    @Resource
    private DYYServiceImpl dyyServiceImpl;

    @Resource
    private RequisitionMapper requisitionMapper;

    @Resource
    private PCBOutMapper pcbOutMapper;


    @Resource
    private UserWorkShopMapper userWorkShopMapper;


    @Resource
    private CalculateItemMapper calculateItemMapper;

    @Resource
    private SurplusMaterialMapper surplusMaterialMapper;


    @Resource
    private IssuanceMapper issuanceMapper;

    @Resource
    private ExportMapper exportMapper;


    private int isflow = 2;


    //简单生产领料单的部门集合
    public static String jiandannos = "432698, 432699, 432700, 432701, 432702, 432703, 432704, 432705, 432706, 432708, 432710, " +
            "432712, 782390, 782391, 782392, 782394, 782395, 1148108, 1148109, 1148110, 1148112, 1148113, 1148114, 1148115, 1160548, " +
            "1160549, 1160550, 1959859, 2457163, 2457164, 2457388, 2458385, 2458386, 2458395, 3472719, 3472720, 3472722, 3499554, 3499556, " +
            "3926391, 3926392, 3926393, 3942677, 4001431, 4001432,372889";

    //发料申请
    @Override
    public void issuance(AddTo to) {

        String id = to.getIssuanceId();

        Issuance issuance1 = issuanceMapper.selectById(id);


        List<CalculateItem> recommendItems1 = to.getRecommendItems();


        List<String> k3nolist = recommendItems1.stream()
                .map(CalculateItem::getK3No)
                .collect(Collectors.toList());

        List<MaterialDetail> materialDetails = stockMapper.findMaterialDetailsByK3Nos(k3nolist);

        // 将查询结果封装成 Map，物料编码作为 key
        Map<String, MaterialDetail> materialDetailMap = materialDetails.stream()
                .collect(Collectors.toMap(
                        MaterialDetail::get物料编码, // 键
                        detail -> detail, // 值
                        (existing, replacement) -> existing // 合并函数，选择保留第一个
                ));


        for (CalculateItem item : to.getRecommendItems()) {


            MaterialDetail detail = materialDetailMap.get(item.getK3No());

            if (detail != null) {
                item.setFEXPIRYDATE(detail.getFEXPIRYDATE());
                item.setFPRODUCEDATE(detail.getFPRODUCEDATE());
                item.setFISKFPERIOD(detail.getFISKFPERIOD());
                item.setFOWNERID(detail.getFOWNERID());
                item.setFSTOCKORGID(detail.getFSTOCKORGID());
                item.setFKEEPERTYPEID(detail.getFKEEPERTYPEID());
                item.setFKEEPERID(detail.getFKEEPERID());
                item.setFOWNERTYPEID(detail.getFOWNERTYPEID());
                item.setFSTOCKID(detail.getFSTOCKLNUMBER());
                item.setFLot(detail.getFFLOTNUMBER());
                item.setFSTOCKSTATUSID(detail.getFSTOCKSTATUSNUMBER());
                item.setFBASEUNITID(detail.getFBASEUNITID());
                item.setFSTOCKUNITID(detail.getFSTOCKUNITID());
                item.setFMaterialId(detail.getFMaterialId());
            }


            if (StringUtils.isNotBlank(item.getBatchNumber()))
                item.setCustcode(stockMapper.findCustCode(item.getBatchNumber()));
            item.setApplicationId(Long.parseLong(id));
            item.setId(null);
            item.setSystemType(4);
            calculateItemMapper.insert(item);
        }

        String token = dyyServiceImpl.getDYYToken();
        String url = "http://qwif.do1.com.cn/qwcgi/api/apiForm/pushFormData.do?token=" + token + "&corpId=wx4f594cea21b39022&id=forma6191da0285c47f0a9e25cafce551712&isFlow=" + isflow;

        // 请求的表单数据
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("foffaa80b9e29a491ca1745a78a9315e1a", "板材");
        fieldMap.put("fob7508dd8a11b4c949a52e28a2b6c872a", issuance1.getNo());

        List<CalculateItem> recommendItems = to.getRecommendItems()
                .stream()
                .filter(item -> item.getK3Name() != null || item.getSurplusType() != null)
                .collect(Collectors.toList());

        // 创建一个数组来存放多个板材项
        List<Map<String, Object>> itemList = new ArrayList<>();
        for (CalculateItem item : recommendItems) {
            Map<String, Object> innerField = new HashMap<>();
            innerField.put("fo6710f43d8efa41bc8397f9b7b67c29a0", item.getType());
            innerField.put("fo70757c2a6221491d878f605d8c0ca42d", item.getPlate());
            innerField.put("fo3e5ad7736eca4fed8c02c3687c5121df", item.getPlateType());
            innerField.put("fo507cfdd61b5f4aaf847cc4956e2b1b27", item.getLength());
            innerField.put("fo4a007e2bedec48dd80cd7f459a164ab4", item.getWidth());
            innerField.put("foadc180e2b35a44f48f52d9eba4b77e89", item.getPlateThickness());
            innerField.put("fo8c1fc6478b1a46309a09ab04281ba56e", item.getCopperThickness());
//            innerField.put("foa897ea3af39e49ec87ef27c2f789041d", String.valueOf(item.getTotal()));
            innerField.put("fo724cb0c1a50844038553b36fbebcc99a", item.getSurplusType());
            if (item.getSurplusNumber() != null)
                innerField.put("foa8eadc26e0cc45c1b25441f60951189a", String.valueOf(item.getSurplusNumber()));


            innerField.put("fo29197bbdb9034224b50591a0d9795447", item.getK3Name());
            if (item.getK3Number() != null)
                innerField.put("fo09534994dd4a4d56a060f2be5d2a9b71", String.valueOf(item.getK3Number()));

            // 添加到数组列表中
            itemList.add(innerField);
        }

        // 将itemList放入字段中
        fieldMap.put("fo840cac985ef64f5a8755a1b668faa65c", itemList);

        // 备注字段
        fieldMap.put("fo7d620c9764224f95849436a0967df3b2", to.getRemark());

        // 请求体数据构造
        String instanceTitle = "板材发放申请";
        String createTime = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        String creator = to.getCreate_no();

        // 使用Jackson库将字段map转换为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String fieldMapJson = null;
        try {
            fieldMapJson = objectMapper.writeValueAsString(fieldMap);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常
        }

        // 构建完整请求数据
        String requestBody = "[\n" +
                "    {\n" +
                "        \"instanceTitle\": \"" + instanceTitle + "\",\n" +
                "        \"createTime\": \"" + createTime + "\",\n" +
                "        \"creator\": \"" + creator + "\",\n" +
                "        \"fieldMap\": " + fieldMapJson + "\n" +
                "    }\n" +
                "]";

        // 使用Hutool的HttpRequest发送POST请求
        String response = HttpRequest.post(url)
                .form("data", requestBody) // 设置请求体中data字段的值为JSON字符串
                .timeout(10000) // 设置超时，10秒
                .execute()
                .body();

        // 打印返回结果
        System.out.println("Response: " + response);


        JSONObject jsonResponse = new JSONObject(response);

        // 检查 code 是否为 0
        if ("0".equals(jsonResponse.getStr("code"))) {
            // 获取 data 部分的 JSONObject
            JSONObject data = jsonResponse.getJSONObject("data");

            // 获取 ids 数组
            JSONArray ids = data.getJSONArray("ids");

            // 提取 ids 数组的第一个元素
            String firstId = ids.getStr(0);

            //保存url
            issuance1.setStatus(1);
            issuance1.setWorkId(firstId);
            issuance1.setUrl("https://qy.do1.com.cn/wxqyh/vp/module/form.html?agentCode=form&isFromPC=true&corp_id=wx4f594cea21b39022#/detail?id=" + firstId);
            issuanceMapper.updateById(issuance1);

        }


    }


    //发起审批


    @Override
    public BaseResult add(AddTo to) throws Exception {

        //先判断数据有没有问题
        if (to.getType() == 1) {
            if (to.getCalculateList() == null || to.getCalculateList().isEmpty()) {
                return new BaseResult(2, "请选择物料");
            }
        } else if (to.getType() == 2) {
            if (to.getNo2list() == null || to.getNo2list().isEmpty()) {
                return new BaseResult(2, "请选择物料");
            }
        }

        Requisition requisition = new Requisition();


        requisition.setStatus(1);


        if (to.getType() == 2 && StringUtils.isNotBlank(to.getWorkShopId())) {
            requisition.setWorkShopId(to.getWorkShopId());
        } else if (to.getType() == 1) {
            requisition.setWorkShopId("490285");
        }


        requisition.setType(to.getType());
        requisition.setRemark(to.getRemark());

        requisition.setCreateBy(to.getCreate_by());
        requisitionMapper.insert(requisition);
        Long id = requisition.getId();

        Requisition requisition1 = requisitionMapper.selectById(id);


        //板材
        if (to.getType() == 1) {

            List<CalculateItem> nolist = to.getNos();
            List<CalculateItem> calculateList = to.getCalculateList();

            // 批量插入，每次提交一定数量的记录
            for (CalculateItem item : nolist) {
                item.setId(null);
                item.setApplicationId(id); // 设置 applicationId
                item.setSystemType(1);
                // 设置 systemType 为 1
                calculateItemMapper.insert(item); // 单条插入
            }

            for (CalculateItem item : calculateList) {
                item.setId(null);
                item.setApplicationId(id); // 设置 applicationId
                item.setSystemType(3);     // 设置 systemType 为 2
                calculateItemMapper.insert(item); // 单条插入
            }


            Issuance issuance = new Issuance();
            issuance.setRequisitionNo(requisition1.getNo());
            issuance.setStatus(3);
            issuance.setRemark(to.getRemark());
            issuance.setType(to.getType());
            issuance.setCreateBy(to.getCreate_no());

            issuance.setWorkShopId("490285");


            issuanceMapper.insert(issuance);


        } else if (to.getType() == 2) {


            Issuance issuance = new Issuance();
            issuance.setRequisitionNo(requisition1.getNo());
            issuance.setStatus(1);
            issuance.setCreateBy(to.getCreate_no());


            issuance.setRemark(to.getRemark());
            issuance.setType(to.getType());

            issuance.setWorkShopId(to.getWorkShopId());
            issuanceMapper.insert(issuance);
            String id2 = issuance.getId();

            Issuance issuance1 = issuanceMapper.selectById(id2);


            //领料相关物料
            List<AddTo.MaterialUItem> no2list = to.getNo2list();


            List<String> k3nolist = no2list.stream()
                    .map(AddTo.MaterialUItem::get物料编码)
                    .collect(Collectors.toList());

            List<MaterialDetail> materialDetails = stockMapper.findMaterialDetailsByK3Nos(k3nolist);

            Map<String, MaterialDetail> materialDetailMap = materialDetails.stream()
                    .filter(detail -> !"CK020".equals(detail.getFSTOCKLNUMBER())) // 先屏蔽FSTOCKLNUMBER为CK020的数据
                    .collect(Collectors.toMap(
                            MaterialDetail::get物料编码, // 键：物料编码
                            detail -> detail,             // 值：物料详情
                            (existing, replacement) -> existing // 如果有重复的键，保留现有的条目（即第一个）
                    ));


            for (AddTo.MaterialUItem item : no2list) {
                CalculateItem tem = new CalculateItem();
                tem.setApplicationId(id);
                tem.setK3No(item.get物料编码());


                tem.setSystemType(2);
                tem.setName(item.get物料名称());
                tem.setType(item.get规格型号());
                tem.setTotal(item.getNum());
                tem.setBalance(item.getBalance());
                tem.setMaterialGroup(item.get物料分组());

                tem.setUnit(item.get基本单位());


                MaterialDetail detail = materialDetailMap.get(item.get物料编码());

                if (detail != null) {
                    tem.setFEXPIRYDATE(detail.getFEXPIRYDATE());
                    tem.setFPRODUCEDATE(detail.getFPRODUCEDATE());
                    tem.setFISKFPERIOD(detail.getFISKFPERIOD());
                    tem.setFOWNERID(detail.getFOWNERID());
                    tem.setFSTOCKORGID(detail.getFSTOCKORGID());
                    tem.setFKEEPERTYPEID(detail.getFKEEPERTYPEID());
                    tem.setFKEEPERID(detail.getFKEEPERID());
                    tem.setFOWNERTYPEID(detail.getFOWNERTYPEID());
                    tem.setFSTOCKID(detail.getFSTOCKLNUMBER());
                    tem.setFSTOCKSTATUSID(detail.getFSTOCKSTATUSNUMBER());
                    tem.setFBASEUNITID(detail.getFBASEUNITID());
                    tem.setFLot(detail.getFFLOTNUMBER());
                    tem.setFSTOCKUNITID(detail.getFSTOCKUNITID());
                    tem.setFMaterialId(detail.getFMaterialId());
                    tem.setRemark(item.getRemark());
                }
                tem.setId(null);
                calculateItemMapper.insert(tem);
                tem.setId(null);
                // 设置 systemType 为 1
                tem.setApplicationId(Long.parseLong(id2));
                tem.setSystemType(4);
                calculateItemMapper.insert(tem);

                // 单条插入
            }


            String token = dyyServiceImpl.getDYYToken();
            String url = "http://qwif.do1.com.cn/qwcgi/api/apiForm/pushFormData.do?token=" + token + "&corpId=wx4f594cea21b39022&id=form43bde11b178243c49cf0bc75f401cdff&isFlow=" + isflow;

            // 请求的表单数据
            Map<String, Object> fieldMap = new HashMap<>();
            fieldMap.put("fo88286033e7074daf80f271f644e14f4c", "辅料");
            fieldMap.put("fo8702d7c972ac44408d73c04710033e74", issuance1.getNo());


            String workShopName = pcbOutMapper.getWorkShopName(to.getWorkShopId());
            fieldMap.put("fo567c80b2c7f44f649416e8f7421d9d67", workShopName);


            // 放入列表
            List<Map<String, Object>> itemList = new ArrayList<>();
            for (AddTo.MaterialUItem item : no2list) {
                // 创建多层嵌套的字段数据
                Map<String, Object> innerField = new HashMap<>();

                innerField.put("fo49b1ae4d387b47ce8be99e6236fe8fe2", item.get物料编码());
                innerField.put("fo3580bfbb10f84a8588444f487aef623d", item.get物料名称());
                innerField.put("fo711dcfa6d7d1412c82dad54d78891966", item.get最小发料批量());
                innerField.put("focb42ab50868a4a7e898162565dac6776", item.get基本单位());
                innerField.put("fo7f3c73c5c4114f8c807cea9213137c57", item.getBalance());//在线结存
                innerField.put("fo74ef17e4033546f1a2db4f3b0977c739", item.getNum());

                String qty = item.getQty();
                String dayUse = "0";  // Default value in case qty is null

                if (qty != null) {
                    dayUse = new BigDecimal(qty).divide(new BigDecimal("30"), 2, BigDecimal.ROUND_HALF_UP).toString();
                }

                innerField.put("fo341b3915181e426396fa655f539bcf5c", dayUse); // 日用量

                innerField.put("fo55d1e0d0a31c42c88ba8c10e462148c7", item.get物料记录日期());//上次领用时间
                innerField.put("fo0fc71450ee3249e3b720cabb2721c48d", item.get物料记录编号());//上次领用数量
                innerField.put("fobecbc342402a41dc8d098eabe7021754", calculateResult(item.getBalance(), item.getNum(), dayUse));//使用天数
                innerField.put("fob9a299ddeceb469c90636dccee18deb7", item.getRemark());//备注


                itemList.add(innerField);
            }

            fieldMap.put("fo8d4fc62278b048ea90cd78bfcb591b86", itemList);
            fieldMap.put("fo01aee395836f4efb866074ca079b2e86", to.getRemark());

            // 请求体数据构造
            String instanceTitle = "辅料发放申请";
            String createTime = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
            String creator = to.getCreate_no();

            // 使用Jackson库将字段map转换为JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String fieldMapJson = null;
            try {
                fieldMapJson = objectMapper.writeValueAsString(fieldMap);
            } catch (Exception e) {
                e.printStackTrace();
                // 处理异常
            }

            // 构建完整请求数据
            String requestBody = "[\n" +
                    "    {\n" +
                    "        \"instanceTitle\": \"" + instanceTitle + "\",\n" +
                    "        \"createTime\": \"" + createTime + "\",\n" +
                    "        \"creator\": \"" + creator + "\",\n" +
                    "        \"fieldMap\": " + fieldMapJson + "\n" +
                    "    }\n" +
                    "]";
            log.info(("流程中心Request: " + requestBody));
            // 使用Hutool的HttpRequest发送POST请求
            String response = HttpRequest.post(url)
                    .form("data", requestBody) // 设置请求体中data字段的值为JSON字符串
                    .timeout(10000) // 设置超时，10秒
                    .execute()
                    .body();

            // 打印返回结果
            System.out.println("Response: " + response);
            log.info(("流程中心Response: " + response));

            JSONObject jsonResponse = new JSONObject(response);

            // 检查 code 是否为 0
            if ("0".equals(jsonResponse.getStr("code"))) {
                // 获取 data 部分的 JSONObject
                JSONObject data = jsonResponse.getJSONObject("data");

                // 获取 ids 数组
                JSONArray ids = data.getJSONArray("ids");

                // 提取 ids 数组的第一个元素
                String firstId = ids.getStr(0);

                //保存url
                issuance1.setWorkId(firstId);
                issuance1.setUrl("https://qy.do1.com.cn/wxqyh/vp/module/form.html?agentCode=form&isFromPC=true&corp_id=wx4f594cea21b39022#/detail?id=" + firstId);
                issuanceMapper.updateById(issuance1);

            }


        }


        return new BaseResult();

    }


    public String calculateResult(double balanceStr, int numStr, String dayUseStr) {
        // 将String转换为BigDecimal
        BigDecimal balance = new BigDecimal(balanceStr);
        BigDecimal num = new BigDecimal(numStr);
        BigDecimal dayUse = new BigDecimal(dayUseStr);

        // 判断除数是否为0，如果是0直接返回0
        if (dayUse.compareTo(BigDecimal.ZERO) == 0) {
            return "0"; // 如果除数为0，返回0
        }

        // 计算 (balance + num) / dayUse，结果保留两位小数
        BigDecimal result = balance.add(num).divide(dayUse, 2, RoundingMode.HALF_UP);

        // 返回结果的字符串
        return result.toString();
    }

    private List<SurplusMaterial> findBySpecificationsLike(String specifications, String length, String width, String plateThickness, String copperThickness) {

        QueryWrapper<SurplusMaterial> queryWrapper = new QueryWrapper<>();
        // 筛选规格
        if (specifications != null && !specifications.isEmpty()) {
            queryWrapper.like("specifications", specifications);
        }


        // 筛选规格
        if (StringUtils.isNotBlank(plateThickness)) {
            queryWrapper.like("plate", plateThickness);
        }

        // 筛选规格
        if (StringUtils.isNotBlank(copperThickness)) {
            queryWrapper.like("copper", copperThickness);
        }


        // 筛选 length，如果转换成功则添加到查询条件中
        if (length != null && !length.isEmpty()) {
            try {
                // 如果长度是小数形式，例如 "486.0000000"，去掉小数点后的部分
                String cleanLength = length.contains(".") ? length.substring(0, length.indexOf(".")) : length;
                Long parsedLength = Long.parseLong(cleanLength);
                queryWrapper.eq("length", parsedLength);
            } catch (NumberFormatException e) {
                // 转换失败，跳过该条件
                // 可以根据需要记录日志或者忽略
            }
        }

        // 筛选 width，如果转换成功则添加到查询条件中
        if (width != null && !width.isEmpty()) {
            try {
                // 如果宽度是小数形式，例如 "486.0000000"，去掉小数点后的部分
                String cleanWidth = width.contains(".") ? width.substring(0, width.indexOf(".")) : width;
                Long parsedWidth = Long.parseLong(cleanWidth);
                queryWrapper.eq("width", parsedWidth);
            } catch (NumberFormatException e) {
                // 转换失败，跳过该条件
                // 可以根据需要记录日志或者忽略
            }
        }


        return surplusMaterialMapper.selectList(queryWrapper);


    }

    public void updateSurplusMaterial(String specifications, double surplusNumber) {

        QueryWrapper<SurplusMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("specifications", specifications);

        SurplusMaterial surplusMaterial = surplusMaterialMapper.selectOne(queryWrapper);

        if (surplusMaterial != null) {
            surplusMaterial.setNum(surplusMaterial.getNum() - (int) surplusNumber);
            surplusMaterial.setUsedNum(surplusMaterial.getUsedNum() + (int) surplusNumber);
            surplusMaterialMapper.updateById(surplusMaterial);
        }
    }

    public static String convertCopperThickness(String copperThickness) {
        // 先尝试将字符串转换为 double
        try {
            double copper = Double.parseDouble(copperThickness);

            // 如果是 0.5，返回 "H/H"
            if (copper == 0.5) {
                return "H/H";
            }

            // 提取整数部分并返回加斜线的字符串
            int integerPart = (int) copper; // 获取整数部分
            return integerPart + "/"; // 将整数部分加上斜线
        } catch (NumberFormatException e) {
            // 如果无法转换为数字，返回一个错误消息
            return "Invalid input";
        }
    }

    public static void extractNumbers(String input) {
        // 正则表达式：提取*前后的数字，允许*周围有非数字字符（包括空格、双引号、冒号等）

    }

    @Override
    public AddTo recomend(Object value, Boolean isdetail) {


// 如果是MyBatis-Plus的查询方式，可以使用QueryWrapper来进行OR条件的查询
        QueryWrapper<Requisition> wrapper = new QueryWrapper<>();
        if (value instanceof String) {
            wrapper.eq("no", value);
        } else if (value instanceof Long) {
            wrapper.eq("id", value);
        }
        List<Requisition> requisitions = requisitionMapper.selectList(wrapper);


        if (requisitions != null && requisitions.size() > 0) {

            Requisition requisition = requisitions.get(0);
            Long id = requisition.getId();


            AddTo to = get(id);


            // 板材才需要系统推荐
            if (to.getType() == 1 && isdetail) {
                List<CalculateItem> nolist = to.getCalculateList();
                List<CalculateItem> recommendItems = new ArrayList<>();

                for (CalculateItem item : nolist) {


                    // 处理surplusType和surplusNumber
                    String type = item.getType();
                    String length = item.getLength();
                    String width = item.getWidth();
                    String copperThickness = item.getCopperThickness();
                    String plateThickness = item.getPlateThickness();
                    String plateType = (item.getPlateType() != null) ? item.getPlateType().trim() : "";


                    //fr-4以外的需要进行匹配
                    if (StringUtils.isNotBlank(item.getPlate()) && !item.getPlate().equals("FR-4")) {


                        if (StringUtils.isNotBlank(copperThickness)) {


                            String copper = convertCopperThickness(copperThickness);
                            Material material = pcbOutMapper.queryBomByItem(plateType, plateThickness, copper);
                            if (material != null) {
                                item.setK3No(material.getMaterialCode());
                                item.setK3Name(material.getMaterialName());


                                //面积
                                BigDecimal lengthcount = new BigDecimal(length);
                                BigDecimal widthcount = new BigDecimal(width);
                                BigDecimal area = lengthcount.multiply(widthcount).multiply(BigDecimal.valueOf(item.getTotal()));
// 查找 '*' 号的位置
                                Pattern pattern = Pattern.compile("(\\d+)\\D*\\*\\D*(\\d+)");
                                Matcher matcher = pattern.matcher(material.getMaterialName());

                                if (matcher.find()) {
                                    // 输出匹配的两个数字
                                    String num1 = matcher.group(1);
                                    String num2 = matcher.group(2);
                                    // 转换为 BigDecimal
                                    BigDecimal firstNumber = new BigDecimal(num1); // 提取前面的数字
                                    BigDecimal secondNumber = new BigDecimal(num2); // 提取后面的数字

                                    //需求
                                    BigDecimal multiply = firstNumber.multiply(secondNumber).multiply(BigDecimal.valueOf(25.4)).multiply(BigDecimal.valueOf(25.4));
                                    BigDecimal result = area.divide(multiply, 0, RoundingMode.UP);
                                    item.setK3Number(result.doubleValue());

                                } else {
                                    item.setK3Number((double) 0);
                                    continue;

                                }


                            } else {
                                item.setK3Number((double) 0);
                            }


                        }


                    }


//                Double total = item.getTotal();

                    // 查询surplus_material表，获取匹配的记录


                    if (StringUtils.isNotBlank(type)) {
                        List<SurplusMaterial> surplusMaterials = findBySpecificationsLike(type, length, width, plateThickness, copperThickness);
                        if (!surplusMaterials.isEmpty()) {
                            SurplusMaterial surplusMaterial = surplusMaterials.get(0);
                            item.setSurplusType(surplusMaterial.getSpecifications());


                            if (item.getK3Number() != null && item.getK3Number() > 0) {
                                int num = surplusMaterial.getNum();
                                item.setSurplusNumber(item.getK3Number() < num ? item.getK3Number() : num);


                                item.setK3Number(item.getK3Number() - item.getSurplusNumber());
                            }


                            item.setSurplusStock(surplusMaterial.getNum());
                        } else {
                            item.setK3Number((double) 0);
                        }
                    }


                    recommendItems.add(item);
                }
//            List<CalculateItem> filteredCalculateItems = recommendItems.stream()
//                    .filter(item -> item.getTotal() > 0)  // 过滤条件：total > 0
//                    .collect(Collectors.toList());
                to.setRecommendItems(recommendItems);
            }

            return to;
        } else {
            return null;
        }


    }


    @Override
    public AddTo getIssuanceDetail(String id) {
        AddTo result = new AddTo();


        Issuance issuance = issuanceMapper.selectById(id);
        if (issuance == null) {
            return null;
        }

        result.setNo(issuance.getNo());
        result.setType(issuance.getType());

        result.setWorkShopId(issuance.getWorkShopId());
        result.setRemark(issuance.getRemark());


        Map<String, Object> map = new HashMap<>();
        map.put("application_id", Long.parseLong(id));
        map.put("system_type", 4);

        if (issuance.getType() == 1) {
            List<CalculateItem> calculateItems = calculateItemMapper.selectByMap(map);
            result.setRecommendItems(calculateItems);


        } else if (issuance.getType() == 2) {

            List<CalculateItem> calculateItems = calculateItemMapper.selectByMap(map);

            List<AddTo.MaterialUItem> items = new java.util.ArrayList<>();

            for (CalculateItem tem : calculateItems) {
                AddTo.MaterialUItem item = new AddTo.MaterialUItem();
                item.set规格型号(tem.getType());
                item.set物料名称(tem.getName());
                item.set物料编码(tem.getK3No());
                item.setNum((int) tem.getTotal());

                item.setBalance(tem.getBalance());


                item.set基本单位(tem.getUnit());
                items.add(item);
            }
            result.setNo2list(items);

        }


        return result;
    }


    public void updateCalculateItems(List<CalculateItem> items, String jsonString) {
        // 解析 JSON 字符串
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONArray details = jsonObject.getJSONObject("data").getJSONArray("details");

        JSONArray reductionItems = details.getJSONObject(0).getJSONObject("data").getJSONArray("fo8d4fc62278b048ea90cd78bfcb591b86");

        if (reductionItems == null || reductionItems.isEmpty()) {


            return;
        }

        // 用于记录哪些 items 被匹配到了
        Set<CalculateItem> matchedItems = new HashSet<>();

        // 遍历 reductionItems
        for (int i = 0; i < reductionItems.size(); i++) {
            JSONObject reductionItem = reductionItems.getJSONObject(i);
            String reducedName = reductionItem.getStr("fo3580bfbb10f84a8588444f487aef623d");
            Double reducedValue = reductionItem.getDouble("fo74ef17e4033546f1a2db4f3b0977c739");

            log.info("需要遍历的CalculateItem为" + items);

            // 查找匹配的项并更新
            for (CalculateItem item : items) {
                if (item.getName().equals(reducedName)) {
                    if (item.getK3Number() != null) {
                        item.setK3Number(reducedValue);
                    }
                    item.setTotal(reducedValue);
                    matchedItems.add(item); // 记录匹配到的 item
                    calculateItemMapper.updateById(item); // 更新到数据库
                }
            }
        }

        // 检查 items 中是否有未匹配到的项
        List<CalculateItem> itemsToRemove = new ArrayList<>();
        for (CalculateItem item : items) {
            if (!matchedItems.contains(item)) {
                itemsToRemove.add(item); // 记录需要删除的 item
                log.info("物控删除了物料:" + item.getName());
                calculateItemMapper.deleteById(item.getId()); // 从数据库中删除
            }
        }

        // 从 items 列表中移除未匹配到的项
        items.removeAll(itemsToRemove);
    }


    //实际处理回调
    @Override
    public void handle(String workid, String jsonString) throws Exception {


        try {
            Map<String, Object> map = new HashMap<>();
            map.put("work_id", workid);

            List<Issuance> issuances = issuanceMapper.selectByMap(map);
            if (issuances == null || issuances.isEmpty()) {
                throw new Exception("没有找到对应工单的发料申请");
            }
            //要发料的申请
            Issuance issuance = issuances.get(0);

            //防抖处理
            if (issuance.getStatus() == 2) {
                return;
            }


            QueryWrapper<CalculateItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("application_id", Long.parseLong(issuance.getId()))
                    .eq("system_type", 4);  // 这里添加了 system_type 为 2 或 4 的条件

            List<CalculateItem> items = calculateItemMapper.selectList(queryWrapper);

            updateCalculateItems(items, jsonString);

            K3CloudApiClient client = new K3CloudApiClient("http://192.168.10.31/k3cloud/");
            Boolean result = client.login("684d23dd8b8b76", "administrator", "KingBrother@20", 2052);


            LocalDateTime now = LocalDateTime.now();

            // 格式化为 "yyyy-MM-dd HH:mm:ss" 格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = now.format(formatter);

            if (result) {


                //板材
                if (issuance.getType() == 1) {


                    boolean exists = items.stream()
                            .anyMatch(item -> item.getK3Number() != null && item.getK3Number() > 0);

                    //存在金蝶的
                    if (exists) {
                        String sContent = "{\n" +
                                "  \"Creator\": \"\",\n" +
                                "  \"NeedUpDateFields\": [],\n" +
                                "  \"NeedReturnFields\": [],\n" +
                                "  \"IsDeleteEntry\": \"True\",\n" +
                                "  \"SubSystemId\": \"\",\n" +
                                "  \"IsVerifyBaseDataField\": \"false\",\n" +
                                "  \"Model\": {\n" +
                                "    \"FID\": \"0\",\n" +
                                "    \"FBillType\": {\n" +
                                "      \"FNumber\": \"JDSCLL01_SYS\"\n" +  //写死
                                "    },\n" +
                                "    \"FDate\": \"" + formattedDate + "\",\n" + // 拼接当前日期
                                "    \"FDescription\": \"" + issuance.getRemark() + "\",\n" +
                                "    \"FStockOrgId\": {\n" +
                                "      \"FNumber\": \"128\"\n" +
                                "    },\n" +
                                "    \"FOwnerTypeId0\": \"BD_OwnerOrg\",\n" +
                                "    \"FOwnerId0\": {\n" +
                                "      \"FNumber\": \"128\"\n" +
                                "    },\n" +
                                "    \"FPrdOrgId\": {\n" +
                                "      \"FNumber\": \"128\"\n" +
                                "    },\n" +
                                "    \"FWorkShopId\": {\n" +
                                "      \"FNumber\": \"C02\"\n" + //固定开料
                                "    },\n" +
                                "    \"FTransferBizTypeId\": {\n" +
                                "      \"FNumber\": \"OverOrgPick\"\n" +
                                "    },\n" +

                                "        \"FOwnerId\": {\n" +
                                "          \"FNumber\": \"128\"\n" +
                                "        },\n" +

                                "    \"FBizType\": \"NORMAL\",\n" +
                                "    \"FEntity\": [\n";

                        Map<String, CalculateItem> mergedItemsMap = items.stream()
                                .filter(item -> item.getK3No() != null && !item.getK3No().isEmpty()) // 过滤掉 k3No 为空的项
                                .collect(Collectors.toMap(
                                        CalculateItem::getK3No, // 使用 k3No 作为 key
                                        item -> item, // 初始值就是当前 item
                                        (existing, newItem) -> {
                                            // 如果 k3No 相同，则合并
                                            Double existingK3Number = existing.getK3Number();
                                            Double newK3Number = newItem.getK3Number();

                                            // 检查 null，避免空指针异常
                                            if (existingK3Number == null) {
                                                existingK3Number = (double) 0;
                                            }
                                            if (newK3Number == null) {
                                                newK3Number = (double) 0;
                                            }

                                            // 执行累加
                                            existing.setK3Number(existingK3Number + newK3Number);

                                            // 其他属性合并，采用某一条数据的值
                                            try {
                                                BeanUtils.copyProperties(existing, newItem);
                                            } catch (Exception e) {
                                                e.printStackTrace(); // 捕获可能的 BeanUtils 异常
                                            }
                                            return existing; // 返回合并后的 item
                                        }
                                ));

                        // 返回合并后的新的 List
                        ArrayList<CalculateItem> calculateItems = new ArrayList<>(mergedItemsMap.values());

                        // 标志位，判断是否有有效的 item
                        boolean hasValidItems = false;


                        List<LastRecord> records = new ArrayList<>();
                        List<Material> allMaterials = pcbOutMapper.queryList();
                        // 这里在FEntity内部循环填充item数据
                        for (CalculateItem item : calculateItems) {
                            if (item.getK3Number() == null || !(item.getK3Number() > 0)) {
                                continue;
                            }


                            LastRecord record = new LastRecord();
                            record.setDate(formattedDate);
                            record.setNo(item.getK3No());
                            record.setNumber(String.valueOf(item.getTotal()));
                            record.setWorkshop(issuance.getWorkShopId());
                            records.add(record);

                            hasValidItems = true;  // 发现有效数据

                            Material material = allMaterials.stream()
                                    .filter(m -> item.getK3No().equals(m.getMaterialCode()))
                                    .findFirst()  // 取第一个匹配的（如果有多个）
                                    .orElse(null);
                            if (material == null) {
                                continue;
                            }

                            sContent += "      {\n" +
                                    "        \"FEntryID\": 0,\n" +
                                    "        \"FMaterialId\": {\n" +
                                    "          \"FNumber\": \"" + item.getK3No() + "\"\n" +
                                    "        },\n" +
                                    "        \"FUnitID\": {\n" +
                                    "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                    "        },\n" +
                                    "        \"FAppQty\": " + item.getK3Number() + ",\n" +
                                    "        \"FActualQty\": " + item.getK3Number() + ",\n" +
                                    "        \"FStockId\": {\n" +
                                    "          \"FNumber\": \"" + item.getFSTOCKID() + "\"\n" +
                                    "        },\n" +

                                    // Add FLot conditionally
                                    (item.getFLot() != null && !item.getFLot().isEmpty() && !item.getFLot().equals("0") ?
                                            "        \"FLot\": {\n" +
                                                    "          \"FNumber\": \"" + item.getFLot() + "\"\n" +
                                                    "        },\n" : "") +

                                    "        \"FIsAffectCost\": false,\n" +
                                    "        \"FStockUnitId\": {\n" +
                                    "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                    "        },\n" +
                                    "        \"FStockActualQty\": " + item.getK3Number() + ",\n" +
                                    "\"FOwnerTypeIdHead\":\"BD_OwnerOrg\",\n" + "        \"FOwnerId\": {\n" +
                                    "          \"FNumber\": \"128\"\n" +
                                    "        },\n" +
                                    "        \"FParentOwnerTypeId\": \"BD_OwnerOrg\",\n";

                            if (item.getFISKFPERIOD() != null && item.getFISKFPERIOD() == 1) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

                                // 格式化 FEXPIRYDATE 和 FPRODUCEDATE
                                String formattedExpiryDate = item.getFEXPIRYDATE() != null ? sdf.format(item.getFEXPIRYDATE()) : null;
                                String formattedProduceDate = item.getFPRODUCEDATE() != null ? sdf.format(item.getFPRODUCEDATE()) : null;

                                sContent +=
                                        "        \"FExpiryDate\": \"" + formattedExpiryDate + "\",\n" + // 格式化后的过期日期
                                                "        \"FProduceDate\": \"" + formattedProduceDate + "\",\n";
                            }
                            //备注
                            if (StringUtils.isNotBlank(item.getFileNumber())) {
                                sContent += "        \"FEntrtyMemo\": \"" + "档案号:" + item.getFileNumber() + "\",\n";
                            }

                            sContent +=


                                    "        \"FAuxPropId\": {\n" +
                                            "        \"FAUXPROPID__FF100001\": \"" + issuance.getRemark() + "\",\n" +

                                            "        \"FAUXPROPID__FF100002\": \"" + issuance.getRemark() + "\"\n" +
                                            "        },\n" +

                                            "        \"FParentOwnerId\": {\n" +
                                            "          \"FNumber\": \"128\"\n" +
                                            "        },\n" +
                                            "        \"FBaseUnitId\": {\n" +
                                            "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                            "        },\n" +
                                            "        \"FBaseActualQty\": " + item.getK3Number() + ",\n" +
                                            "        \"FStockStatusId\": {\n" +
                                            "          \"FNumber\": \"" + item.getFSTOCKSTATUSID() + "\"\n" +
                                            "        },\n" +
                                            "        \"FBaseAppQty\": " + item.getK3Number() + ",\n" +
                                            "\"FKeeperTypeId\":\"BD_KeeperOrg\",\n" +
                                            "        \"FKeeperId\": {\n" +
                                            "          \"FNumber\": \"128\"\n" +
                                            "        }\n" +
                                            "      },\n";
                        }

                        // 如果没有有效的 item 数据，则移除 FEntity 部分
                        if (!hasValidItems) {
                            sContent = sContent.substring(0, sContent.lastIndexOf("\"FEntity\": [")) + "\"FEntity\": []";
                        } else {
                            // 移除最后一个逗号并闭合FEntity数组和Model对象
                            sContent = sContent.substring(0, sContent.length() - 2); // 去除最后一个逗号
                            sContent += "\n    ]\n" +
                                    "  }\n" +
                                    "}\n";
                        }

                        log.info("金蝶请求体:" + sContent);
                        String sResult = client.save("SP_PickMtrl", sContent);
                        log.info("金蝶回调结果:" + sResult);
                        MessageUtil.sentMessage("25313", sResult, "金蝶回调结果");
                        System.out.println("CurrencyTest success:" + sResult);


                        try {
                            // 使用Hutool的JSON工具解析
                            JSONObject jsonObject = JSONUtil.parseObj(sResult);

                            // 检查是否成功
                            boolean isSuccess = jsonObject.getByPath("Result.ResponseStatus.IsSuccess", Boolean.class);
                            if (isSuccess) {
                                // 提取Number字段
                                String number = jsonObject.getByPath("Result.Number", String.class);
                                if (StringUtils.isNotBlank(number)) {
                                    System.out.println("Extracted Number: " + number);

                                    issuance.setStatus(2);

                                    //设置当前时间
                                    issuance.setUpdateTime(new Date());
                                    issuance.setReceiptNumber(number);
                                    issuanceMapper.updateById(issuance);

                                    String requisitionNo = issuance.getRequisitionNo();

                                    Map<String, Object> requisitionmap = new HashMap<>();
                                    requisitionmap.put("no", requisitionNo);


                                    List<Requisition> requisitions = requisitionMapper.selectByMap(requisitionmap);
                                    if (requisitions != null && requisitions.size() > 0) {
                                        Requisition requisition = requisitions.get(0);
                                        requisition.setStatus(2);
                                        requisitionMapper.updateById(requisition);
                                    }

                                    log.info("即将插入记录:" + records);
                                    //进行记录
                                    for (LastRecord record : records) {
                                        pcbOutMapper.insertRecord(record);
                                    }


                                }
                            } else {
                                System.out.println("Response status is not successful.");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("An error occurred while parsing the response.");
                        }

                    }


                    List<CalculateItem> filteredItems = items.stream()
                            .filter(item -> item.getSurplusNumber() != null && item.getSurplusNumber() > 0)
                            .collect(Collectors.toList());

                    //存在余料的
                    if (filteredItems != null && filteredItems.size() > 0) {
                        for (CalculateItem item : filteredItems) {


                            updateSurplusMaterial(item.getSurplusType(), item.getSurplusNumber());

                        }


                        issuance.setStatus(2);
                        issuanceMapper.updateById(issuance);

                        String requisitionNo = issuance.getRequisitionNo();

                        Map<String, Object> requisitionmap = new HashMap<>();
                        requisitionmap.put("no", requisitionNo);


                        List<Requisition> requisitions = requisitionMapper.selectByMap(requisitionmap);
                        if (requisitions != null && requisitions.size() > 0) {
                            Requisition requisition = requisitions.get(0);
                            requisition.setStatus(2);
                            requisitionMapper.updateById(requisition);
                        }


                    }


                }


                //辅料
                else if (issuance.getType() == 2) {
                    //待发料
                    issuance.setStatus(3);
                    issuance.setJsondata(jsonString);
                    issuanceMapper.updateById(issuance);

                    String content = "发料单号:" + issuance.getNo() + "已通过审批，请前往系统进行发料";
//                    MessageUtil.sentMessage("25313", content, "物料发料提醒");
                    MessageUtil.sentMessage("16967", content, "物料发料提醒");
                    MessageUtil.sentMessage("00423", content, "物料发料提醒");

                }


            }
        } catch (Exception e) {
            log.error("流程中心回调出错:" + e.getMessage());
            throw new RuntimeException(e);
        }


    }


    @Override
    public void toHandle(String id, String person) throws Exception {

        LocalDateTime now = LocalDateTime.now();

        // 格式化为 "yyyy-MM-dd HH:mm:ss" 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = now.format(formatter);

        Issuance issuance = issuanceMapper.selectById(id);

        QueryWrapper<CalculateItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("application_id", Long.parseLong(issuance.getId()))
                .eq("system_type", 4);  // 这里添加了 system_type 为 2 或 4 的条件

        List<CalculateItem> items = calculateItemMapper.selectList(queryWrapper);

// 分别筛选出包含 CK013 和不包含 CK013 的项
        List<CalculateItem> ck013Items = items.stream()
                .filter(item -> "CK013".equals(item.getFSTOCKID()))
                .collect(Collectors.toList());

        List<CalculateItem> nonCk013Items = items.stream()
                .filter(item -> !"CK013".equals(item.getFSTOCKID()))
                .collect(Collectors.toList());


        //是否要走其他
        boolean containsCK013 = ck013Items.size() > 0;

        boolean containsNoCK013 = nonCk013Items.size() > 0;


        K3WorkShop departmentNumberByRkey = pcbOutMapper.getDepartmentNumberByRkey(issuance.getWorkShopId());


        List<MonthUse> monthUseList = new ArrayList<>();

        K3CloudApiClient client = new K3CloudApiClient("http://192.168.10.31/k3cloud/");
        Boolean result = client.login("684d23dd8b8b76", "administrator", "KingBrother@20", 2052);

        String prefix = "";
        if (result) {
            List<Material> allMaterials = pcbOutMapper.queryList();
            // 领料部门的逻辑
            if (departmentNumberByRkey.getDeptproperty().equals("4866f13a3a3940b9b2fe47895a6e7cbe")) {

                //简单生产单
                if (containsNoCK013) {

                    //药水需要和别的分开发，发两单


                    List<CalculateItem> yaoshui = nonCk013Items.stream()
                            .filter(item -> "药水".equals(item.getMaterialGroup()))
                            .collect(Collectors.toList());

                    List<CalculateItem> noYaoshui = nonCk013Items.stream()
                            .filter(item -> !"药水".equals(item.getMaterialGroup()))
                            .collect(Collectors.toList());


                    //药水发一单
                    if (yaoshui != null && yaoshui.size() > 0) {

                        String sContent = "{\n" +
                                "  \"Creator\": \"\",\n" +
                                "  \"NeedUpDateFields\": [],\n" +
                                "  \"NeedReturnFields\": [],\n" +
                                "  \"IsDeleteEntry\": \"True\",\n" +
                                "  \"SubSystemId\": \"\",\n" +
                                "  \"IsVerifyBaseDataField\": \"false\",\n" +
                                "  \"Model\": {\n" +
                                "    \"FID\": \"0\",\n" +
                                "    \"FBillType\": {\n" +
                                "      \"FNumber\": \"JDSCLL01_SYS\"\n" +  //写死
                                "    },\n" +
                                "    \"FDate\": \"" + formattedDate + "\",\n" + // 拼接当前日期
                                "    \"FDescription\": \"" + issuance.getRemark() + "\",\n" +
                                "    \"FStockOrgId\": {\n" +
                                "      \"FNumber\": \"128\"\n" + //写死
                                "    },\n" +
                                "    \"FOwnerTypeId0\": \"BD_OwnerOrg\",\n" +
                                "    \"FOwnerId0\": {\n" +
                                "      \"FNumber\": \"128\"\n" + //写死
                                "    },\n" +
                                "    \"FPrdOrgId\": {\n" +
                                "      \"FNumber\": \"128\"\n" +
                                "    },\n" +
                                "    \"FWorkShopId\": {\n" +
                                "    \"FNumber\": \"" + departmentNumberByRkey.get部门编码() + "\",\n" +
                                "    },\n" +
                                "    \"FTransferBizTypeId\": {\n" +
                                "      \"FNumber\": \"OverOrgPick\"\n" +
                                "    },\n" +

                                "        \"FOwnerId\": {\n" +
                                "          \"FNumber\": \"128\"\n" + //写死
                                "        },\n" +

                                "    \"FBizType\": \"NORMAL\",\n" +
                                "    \"FEntity\": [\n";

                        List<LastRecord> records = new ArrayList<>();
                        // 这里在FEntity内部循环填充item数据
                        for (CalculateItem item : yaoshui) {
                            if (!(item.getTotal() > 0)) {
                                continue;
                            }

                            LastRecord record = new LastRecord();
                            record.setDate(formattedDate);
                            record.setNo(item.getK3No());
                            record.setNumber(String.valueOf(item.getTotal()));
                            record.setWorkshop(issuance.getWorkShopId());
                            records.add(record);

                            MonthUse use = new MonthUse();
                            use.setQty("0.00");
                            use.setWorkshop(issuance.getWorkShopId());
                            use.setCode(item.getK3No());
                            monthUseList.add(use);


                            Material material = allMaterials.stream()
                                    .filter(m -> item.getK3No().equals(m.getMaterialCode()))
                                    .findFirst()  // 取第一个匹配的（如果有多个）
                                    .orElse(null);
                            if (material == null) {
                                continue;
                            }

                            sContent += "      {\n" +
                                    "        \"FEntryID\": 0,\n" +
                                    "        \"FMaterialId\": {\n" +
                                    "          \"FNumber\": \"" + item.getK3No() + "\"\n" +
                                    "        },\n" +
                                    "        \"FUnitID\": {\n" +
                                    "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                    "        },\n" +
                                    "        \"FAppQty\": " + item.getTotal() + ",\n" +
                                    "        \"FActualQty\": " + item.getTotal() + ",\n" +
                                    "        \"FStockId\": {\n" +
                                    "          \"FNumber\": \"" + item.getFSTOCKID() + "\"\n" +
                                    "        },\n" +

                                    // Add FLot conditionally
                                    (item.getFLot() != null && !item.getFLot().isEmpty() && !item.getFLot().equals("0") ?
                                            "        \"FLot\": {\n" +
                                                    "          \"FNumber\": \"" + item.getFLot() + "\"\n" +
                                                    "        },\n" : "") +

                                    "        \"FIsAffectCost\": false,\n" +
                                    "        \"FStockUnitId\": {\n" +
                                    "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                    "        },\n" +
                                    "        \"FStockActualQty\": " + item.getTotal() + ",\n" +
                                    "\"FOwnerTypeIdHead\":\"BD_OwnerOrg\",\n" + "        \"FOwnerId\": {\n" +
                                    "          \"FNumber\": \"128\"\n" + //写死
                                    "        },\n" +
                                    "        \"FParentOwnerTypeId\": \"BD_OwnerOrg\",\n";

                            if (item.getFISKFPERIOD() != null && item.getFISKFPERIOD() == 1) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                                // 格式化 FEXPIRYDATE 和 FPRODUCEDATE
                                String formattedExpiryDate = item.getFEXPIRYDATE() != null ? sdf.format(item.getFEXPIRYDATE()) : null;
                                String formattedProduceDate = item.getFPRODUCEDATE() != null ? sdf.format(item.getFPRODUCEDATE()) : null;

                                sContent +=
                                        "        \"FExpiryDate\": \"" + formattedExpiryDate + "\",\n" + // 格式化后的过期日期
                                                "        \"FProduceDate\": \"" + formattedProduceDate + "\",\n";
                            }

                            sContent +=
                                    "        \"FAuxPropId\": {\n" +
                                            "        \"FAUXPROPID__FF100001\": \"" + issuance.getRemark() + "\",\n" +

                                            "        \"FAUXPROPID__FF100002\": \"" + issuance.getRemark() + "\"\n" +
                                            "        },\n" +

                                            "        \"FParentOwnerId\": {\n" +
                                            "          \"FNumber\": \"128\"\n" + //写死
                                            "        },\n" +
                                            "        \"FBaseUnitId\": {\n" +
                                            "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                            "        },\n" +
                                            "        \"FBaseActualQty\": " + item.getTotal() + ",\n" +
                                            "        \"FStockStatusId\": {\n" +
                                            "          \"FNumber\": \"" + item.getFSTOCKSTATUSID() + "\"\n" +
                                            "        },\n" +
                                            "        \"FBaseAppQty\": " + item.getTotal() + ",\n" +
                                            "\"FKeeperTypeId\":\"BD_KeeperOrg\",\n" +
                                            "        \"FKeeperId\": {\n" +
                                            "          \"FNumber\": \"128\"\n" + //写死
                                            "        }\n" +
                                            "      },\n";
                        }


                        // 移除最后一个逗号并闭合FEntity数组和Model对象
                        sContent = sContent.substring(0, sContent.length() - 2); // 去除最后一个逗号
                        sContent += "\n    ]\n" +
                                "  }\n" +
                                "}\n";
                        log.info("金蝶请求体:" + sContent);
                        String sResult = client.save("SP_PickMtrl", sContent);
                        log.info("金蝶回调结果:" + sResult);
//            MessageUtil.sentMessage("25313",sResult, "金蝶回调结果");
                        System.out.println("CurrencyTest success:" + sResult);


                        try {
                            // 使用Hutool的JSON工具解析
                            JSONObject jsonObject = JSONUtil.parseObj(sResult);

                            // 检查是否成功
                            boolean isSuccess = jsonObject.getByPath("Result.ResponseStatus.IsSuccess", Boolean.class);
                            if (isSuccess) {
                                // 提取Number字段
                                String number = jsonObject.getByPath("Result.Number", String.class);
                                if (StringUtils.isNotBlank(number)) {
                                    System.out.println("金蝶单号: " + number);

                                    issuance.setStatus(2);
                                    issuance.setUpdateTime(new Date());
                                    issuance.setUpdateBy(person);

                                    if (StringUtils.isNotBlank(prefix)) {
                                        prefix = prefix + "," + number;
                                        issuance.setReceiptNumber(prefix);

                                    } else {
                                        prefix = number;
                                        issuance.setReceiptNumber(number);
                                    }

                                    issuanceMapper.updateById(issuance);

                                    String requisitionNo = issuance.getRequisitionNo();

                                    Map<String, Object> requisitionmap = new HashMap<>();
                                    requisitionmap.put("no", requisitionNo);


                                    List<Requisition> requisitions = requisitionMapper.selectByMap(requisitionmap);
                                    if (requisitions != null && requisitions.size() > 0) {
                                        Requisition requisition = requisitions.get(0);
                                        requisition.setStatus(2);
                                        requisitionMapper.updateById(requisition);
                                    }
                                    log.info("即将插入记录:" + records);
                                    //进行记录
                                    for (LastRecord record : records) {
                                        pcbOutMapper.insertRecord(record);
                                    }


                                    log.info("即将插入月用量:" + monthUseList);
                                    pcbOutMapper.issuanceInsertList(monthUseList);


                                }
                            } else {
                                MessageUtil.sentMessage("25313", sResult, "金蝶回调结果失败");
                                System.out.println("Response status is not successful.");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("An error occurred while parsing the response.");
                        }
                    }


                    if (noYaoshui != null && noYaoshui.size() > 0) {

                        String sContent = "{\n" +
                                "  \"Creator\": \"\",\n" +
                                "  \"NeedUpDateFields\": [],\n" +
                                "  \"NeedReturnFields\": [],\n" +
                                "  \"IsDeleteEntry\": \"True\",\n" +
                                "  \"SubSystemId\": \"\",\n" +
                                "  \"IsVerifyBaseDataField\": \"false\",\n" +
                                "  \"Model\": {\n" +
                                "    \"FID\": \"0\",\n" +
                                "    \"FBillType\": {\n" +
                                "      \"FNumber\": \"JDSCLL01_SYS\"\n" +  //写死
                                "    },\n" +
                                "    \"FDate\": \"" + formattedDate + "\",\n" + // 拼接当前日期
                                "    \"FDescription\": \"" + issuance.getRemark() + "\",\n" +
                                "    \"FStockOrgId\": {\n" +
                                "      \"FNumber\": \"128\"\n" + //写死
                                "    },\n" +
                                "    \"FOwnerTypeId0\": \"BD_OwnerOrg\",\n" +
                                "    \"FOwnerId0\": {\n" +
                                "      \"FNumber\": \"128\"\n" + //写死
                                "    },\n" +
                                "    \"FPrdOrgId\": {\n" +
                                "      \"FNumber\": \"128\"\n" +
                                "    },\n" +
                                "    \"FWorkShopId\": {\n" +
                                "    \"FNumber\": \"" + departmentNumberByRkey.get部门编码() + "\"\n" +
                                "    },\n" +
                                "    \"FTransferBizTypeId\": {\n" +
                                "      \"FNumber\": \"OverOrgPick\"\n" +
                                "    },\n" +

                                "        \"FOwnerId\": {\n" +
                                "          \"FNumber\": \"128\"\n" + //写死
                                "        },\n" +

                                "    \"FBizType\": \"NORMAL\",\n" +
                                "    \"FEntity\": [\n";

                        List<LastRecord> records = new ArrayList<>();
                        // 这里在FEntity内部循环填充item数据
                        for (CalculateItem item : noYaoshui) {
                            if (!(item.getTotal() > 0)) {
                                continue;
                            }

                            LastRecord record = new LastRecord();
                            record.setDate(formattedDate);
                            record.setNo(item.getK3No());
                            record.setNumber(String.valueOf(item.getTotal()));
                            record.setWorkshop(issuance.getWorkShopId());
                            records.add(record);

                            MonthUse use = new MonthUse();
                            use.setQty("0.00");
                            use.setWorkshop(issuance.getWorkShopId());
                            use.setCode(item.getK3No());
                            monthUseList.add(use);


                            Material material = allMaterials.stream()
                                    .filter(m -> item.getK3No().equals(m.getMaterialCode()))
                                    .findFirst()  // 取第一个匹配的（如果有多个）
                                    .orElse(null);
                            if (material == null) {
                                continue;
                            }

                            sContent += "      {\n" +
                                    "        \"FEntryID\": 0,\n" +
                                    "        \"FMaterialId\": {\n" +
                                    "          \"FNumber\": \"" + item.getK3No() + "\"\n" +
                                    "        },\n" +
                                    "        \"FUnitID\": {\n" +
                                    "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                    "        },\n" +
                                    "        \"FAppQty\": " + item.getTotal() + ",\n" +
                                    "        \"FActualQty\": " + item.getTotal() + ",\n" +
                                    "        \"FStockId\": {\n" +
                                    "          \"FNumber\": \"" + item.getFSTOCKID() + "\"\n" +
                                    "        },\n" +

                                    // Add FLot conditionally
                                    (item.getFLot() != null && !item.getFLot().isEmpty() && !item.getFLot().equals("0") ?
                                            "        \"FLot\": {\n" +
                                                    "          \"FNumber\": \"" + item.getFLot() + "\"\n" +
                                                    "        },\n" : "") +

                                    "        \"FIsAffectCost\": false,\n" +
                                    "        \"FStockUnitId\": {\n" +
                                    "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                    "        },\n" +
                                    "        \"FStockActualQty\": " + item.getTotal() + ",\n" +
                                    "\"FOwnerTypeIdHead\":\"BD_OwnerOrg\",\n" + "        \"FOwnerId\": {\n" +
                                    "          \"FNumber\": \"128\"\n" + //写死
                                    "        },\n" +
                                    "        \"FParentOwnerTypeId\": \"BD_OwnerOrg\",\n";

                            if (item.getFISKFPERIOD() != null && item.getFISKFPERIOD() == 1) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                                // 格式化 FEXPIRYDATE 和 FPRODUCEDATE
                                String formattedExpiryDate = item.getFEXPIRYDATE() != null ? sdf.format(item.getFEXPIRYDATE()) : null;
                                String formattedProduceDate = item.getFPRODUCEDATE() != null ? sdf.format(item.getFPRODUCEDATE()) : null;

                                sContent +=
                                        "        \"FExpiryDate\": \"" + formattedExpiryDate + "\",\n" + // 格式化后的过期日期
                                                "        \"FProduceDate\": \"" + formattedProduceDate + "\",\n";
                            }

                            sContent +=
                                    "        \"FAuxPropId\": {\n" +
                                            "        \"FAUXPROPID__FF100001\": \"" + issuance.getRemark() + "\",\n" +

                                            "        \"FAUXPROPID__FF100002\": \"" + issuance.getRemark() + "\"\n" +
                                            "        },\n" +

                                            "        \"FParentOwnerId\": {\n" +
                                            "          \"FNumber\": \"128\"\n" + //写死
                                            "        },\n" +
                                            "        \"FBaseUnitId\": {\n" +
                                            "          \"FNumber\": \"" + material.getBaseUnit() + "\"\n" +
                                            "        },\n" +
                                            "        \"FBaseActualQty\": " + item.getTotal() + ",\n" +
                                            "        \"FStockStatusId\": {\n" +
                                            "          \"FNumber\": \"" + item.getFSTOCKSTATUSID() + "\"\n" +
                                            "        },\n" +
                                            "        \"FBaseAppQty\": " + item.getTotal() + ",\n" +
                                            "\"FKeeperTypeId\":\"BD_KeeperOrg\",\n" +
                                            "        \"FKeeperId\": {\n" +
                                            "          \"FNumber\": \"128\"\n" + //写死
                                            "        }\n" +
                                            "      },\n";
                        }


                        // 移除最后一个逗号并闭合FEntity数组和Model对象
                        sContent = sContent.substring(0, sContent.length() - 2); // 去除最后一个逗号
                        sContent += "\n    ]\n" +
                                "  }\n" +
                                "}\n";
                        log.info("金蝶请求体:" + sContent);
                        String sResult = client.save("SP_PickMtrl", sContent);
                        log.info("金蝶回调结果:" + sResult);
//            MessageUtil.sentMessage("25313",sResult, "金蝶回调结果");
                        System.out.println("CurrencyTest success:" + sResult);


                        try {
                            // 使用Hutool的JSON工具解析
                            JSONObject jsonObject = JSONUtil.parseObj(sResult);

                            // 检查是否成功
                            boolean isSuccess = jsonObject.getByPath("Result.ResponseStatus.IsSuccess", Boolean.class);
                            if (isSuccess) {
                                // 提取Number字段
                                String number = jsonObject.getByPath("Result.Number", String.class);
                                if (StringUtils.isNotBlank(number)) {
                                    System.out.println("金蝶单号: " + number);

                                    issuance.setStatus(2);
                                    issuance.setUpdateTime(new Date());
                                    issuance.setUpdateBy(person);


                                    if (StringUtils.isNotBlank(prefix)) {
                                        prefix = prefix + "," + number;
                                        issuance.setReceiptNumber(prefix);

                                    } else {
                                        prefix = number;
                                        issuance.setReceiptNumber(number);
                                    }

                                    issuanceMapper.updateById(issuance);

                                    String requisitionNo = issuance.getRequisitionNo();

                                    Map<String, Object> requisitionmap = new HashMap<>();
                                    requisitionmap.put("no", requisitionNo);


                                    List<Requisition> requisitions = requisitionMapper.selectByMap(requisitionmap);
                                    if (requisitions != null && requisitions.size() > 0) {
                                        Requisition requisition = requisitions.get(0);
                                        requisition.setStatus(2);
                                        requisitionMapper.updateById(requisition);
                                    }
                                    log.info("即将插入记录:" + records);
                                    //进行记录
                                    for (LastRecord record : records) {
                                        pcbOutMapper.insertRecord(record);
                                    }


                                    log.info("即将插入月用量:" + monthUseList);
                                    pcbOutMapper.issuanceInsertList(monthUseList);


                                }
                            } else {
                                MessageUtil.sentMessage("25313", sResult, "金蝶回调结果失败");
                                System.out.println("Response status is not successful.");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("An error occurred while parsing the response.");
                        }
                    }

                }
                // 走其他生产单逻辑
                // 这里放置其他生产单的具体逻辑代码
                if (containsCK013) {
                    String jsonString = "{\n" +
                            "\"Model\":{\n" +
                            "\"FID\":\"0\",\n" +
                            "\"FBillTypeID\":{\n" +
                            "\"FNumber\":\"QTCKD06_SYS\"\n" + // 单据类型，写死
                            "},\n" +
                            "\"FStockOrgId\":{\n" +
                            "\"FNumber\":\"128\"\n" + // 写死
                            "},\n" +
                            "\"FPickOrgId\":{\n" +
                            "\"FNumber\":\"128\"\n" + // 写死
                            "},\n" +
                            "\"FStockDirect\":\"GENERAL\",\n" + // 库存方向 写死
                            "\"FDate\": \"" + formattedDate + "\",\n" + // 拼接当前日期
                            "\"FDeptId\":{\n" +
                            "\"FNumber\":\"" + departmentNumberByRkey.get部门编码() + "\"\n" + // 部门编码
                            "},\n" +
                            "\"FBizType\":\"0\",\n" +// 业务类型 写死
                            "\"FOwnerTypeIdHead\":\"BD_OwnerOrg\",\n" + // 货主类型 写死
                            "\"FOwnerIdHead\":{\n" +
                            "\"FNumber\":\"128\"\n" + // 写死
                            "},\n" +

                            "\"FEntity\": [\n";

                    List<LastRecord> records = new ArrayList<>();
// 遍历 items 列表，填充 FEntity 数组


                    for (int i = 0; i < ck013Items.size(); i++) {

                        CalculateItem item = ck013Items.get(i);

                        if (!(item.getTotal() > 0)) {
                            continue;
                        }

                        LastRecord record = new LastRecord();
                        record.setDate(formattedDate);
                        record.setNo(item.getK3No());
                        record.setWorkshop(issuance.getWorkShopId());
                        record.setNumber(String.valueOf(item.getTotal()));
                        records.add(record);

                        MonthUse use = new MonthUse();
                        use.setQty("0.00");
                        use.setWorkshop(issuance.getWorkShopId());
                        use.setCode(item.getK3No());
                        monthUseList.add(use);

                        Material material = allMaterials.stream()
                                .filter(m -> item.getK3No().equals(m.getMaterialCode()))
                                .findFirst()  // 取第一个匹配的（如果有多个）
                                .orElse(null);
                        if (material == null) {
                            continue;
                        }

                        jsonString += "{\n" +
                                "\"FMaterialId\":{\n" +
                                "\"FNumber\":\"" + item.getK3No() + "\"\n" + // 填充物料编号
                                "},\n" +
                                "\"FUnitID\":{\n" +
                                "\"FNumber\":\"" + material.getBaseUnit() + "\"\n" + // 单位
                                "},\n" +
                                "\"FQty\":" + item.getTotal() + ",\n" + // 数量
                                "\"FBaseUnitId\":{\n" +
                                "\"FNumber\":\"" + material.getBaseUnit() + "\"\n" + // 单位
                                "},\n" +
                                "\"FStockId\":{\n" +
                                "\"FNumber\":\"" + item.getFSTOCKID() + "\"\n" + // 写死
                                "},\n" +
                                // Add FLot conditionally
                                (item.getFLot() != null && !item.getFLot().isEmpty() && !item.getFLot().equals("0") ?
                                        "        \"FLot\": {\n" +
                                                "          \"FNumber\": \"" + item.getFLot() + "\"\n" +
                                                "        },\n" : "") +
                                "        \"FStockStatusId\": {\n" +
                                "          \"FNumber\": \"" + item.getFSTOCKSTATUSID() + "\"\n" +
                                "        },\n" +

                                "\"FKeeperTypeId\":\"BD_KeeperOrg\",\n" +
                                "\"FOwnerId\":{\n" +
                                "\"FNumber\":\"128\"\n" + // 写死
                                "},\n" +
                                "\"FKeeperId\":{\n" +
                                "\"FNumber\":\"128\"\n" + // 写死
                                "},\n" +
                                "\"FFinUnit\":{\n" +
                                "\"FNumber\":\"" + material.getBaseUnit() + "\"\n" + // 单位
                                "}\n";

                        if (item.getFISKFPERIOD() != null && item.getFISKFPERIOD() == 1) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            // 格式化 FEXPIRYDATE 和 FPRODUCEDATE
                            String formattedExpiryDate = item.getFEXPIRYDATE() != null ? sdf.format(item.getFEXPIRYDATE()) : null;
                            String formattedProduceDate = item.getFPRODUCEDATE() != null ? sdf.format(item.getFPRODUCEDATE()) : null;

                            jsonString +=
                                    "        ,\"FExpiryDate\": \"" + formattedExpiryDate + "\",\n" + // 格式化后的过期日期
                                            "        \"FProduceDate\": \"" + formattedProduceDate + "\"\n";
                        }

                        // 如果不是最后一个元素，添加逗号
                        if (i < items.size() - 1) {
                            jsonString += "},\n";
                        } else {
                            jsonString += "}\n";
                        }
                    }

// 最终的 JSON 字符串


// 结束 FEntity 和 Model 部分
                    jsonString += "]\n";
                    jsonString += "}\n";
                    jsonString += "}";


                    log.info("金蝶其他出库单请求体:" + jsonString);
                    String sResult = client.save("STK_MisDelivery", jsonString);
                    log.info("金蝶其他出库单回调结果:" + sResult);
//            MessageUtil.sentMessage("25313",sResult, "金蝶回调结果");


                    try {
                        // 使用Hutool的JSON工具解析
                        JSONObject jsonObject = JSONUtil.parseObj(sResult);

                        // 检查是否成功
                        boolean isSuccess = jsonObject.getByPath("Result.ResponseStatus.IsSuccess", Boolean.class);
                        if (isSuccess) {
                            // 提取Number字段
                            String number = jsonObject.getByPath("Result.ResponseStatus.SuccessEntitys[0].Number", String.class);

                            if (StringUtils.isNotBlank(number)) {
                                System.out.println("金蝶单号: " + number);

                                issuance.setStatus(2);
                                issuance.setUpdateTime(new Date());
                                issuance.setUpdateBy(person);

                                if (StringUtils.isNotBlank(prefix)) {
                                    issuance.setReceiptNumber(prefix + "," + number);
                                } else {
                                    issuance.setReceiptNumber(number);
                                }

                                issuanceMapper.updateById(issuance);

                                String requisitionNo = issuance.getRequisitionNo();

                                Map<String, Object> requisitionmap = new HashMap<>();
                                requisitionmap.put("no", requisitionNo);


                                List<Requisition> requisitions = requisitionMapper.selectByMap(requisitionmap);
                                if (requisitions != null && requisitions.size() > 0) {
                                    Requisition requisition = requisitions.get(0);
                                    requisition.setStatus(2);
                                    requisitionMapper.updateById(requisition);
                                }
                                log.info("即将插入记录:" + records);
                                //进行记录
                                for (LastRecord record : records) {
                                    pcbOutMapper.insertRecord(record);
                                }


                                log.info("即将插入月用量:" + monthUseList);
                                pcbOutMapper.issuanceInsertList(monthUseList);


                            }
                        } else {
                            MessageUtil.sentMessage("25313", sResult, "金蝶回调结果失败");
                            System.out.println("Response status is not successful.");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("An error occurred while parsing the response.");
                    }
                }
            }
            // 不是领料部门，走其他生产单逻辑
            // 这里放置其他生产单的具体逻辑代码
            else {
                String jsonString = "{\n" +
                        "\"Model\":{\n" +
                        "\"FID\":\"0\",\n" +
                        "\"FBillTypeID\":{\n" +
                        "\"FNumber\":\"QTCKD01_SYS\"\n" + // 单据类型，写死
                        "},\n" +
                        "\"FStockOrgId\":{\n" +
                        "\"FNumber\":\"128\"\n" + // 写死
                        "},\n" +
                        "\"FPickOrgId\":{\n" +
                        "\"FNumber\":\"128\"\n" + // 写死
                        "},\n" +
                        "\"FStockDirect\":\"GENERAL\",\n" + // 库存方向 写死
                        "\"FDate\": \"" + formattedDate + "\",\n" + // 拼接当前日期
                        "\"FDeptId\":{\n" +
                        "\"FNumber\":\"" + departmentNumberByRkey.get部门编码() + "\"\n" + // 部门编码
                        "},\n" +
                        "\"FBizType\":\"0\",\n" +// 业务类型 写死
                        "\"FOwnerTypeIdHead\":\"BD_OwnerOrg\",\n" + // 货主类型 写死
                        "\"FOwnerIdHead\":{\n" +
                        "\"FNumber\":\"128\"\n" + // 写死
                        "},\n" +

                        "\"FEntity\": [\n";

                List<LastRecord> records = new ArrayList<>();
// 遍历 items 列表，填充 FEntity 数组


                for (int i = 0; i < items.size(); i++) {

                    CalculateItem item = items.get(i);

                    if (!(item.getTotal() > 0)) {
                        continue;
                    }

                    LastRecord record = new LastRecord();
                    record.setDate(formattedDate);
                    record.setWorkshop(issuance.getWorkShopId());
                    record.setNo(item.getK3No());
                    record.setNumber(String.valueOf(item.getTotal()));
                    records.add(record);

                    MonthUse use = new MonthUse();
                    use.setQty("0.00");
                    use.setWorkshop(issuance.getWorkShopId());
                    use.setCode(item.getK3No());
                    monthUseList.add(use);

                    Material material = allMaterials.stream()
                            .filter(m -> item.getK3No().equals(m.getMaterialCode()))
                            .findFirst()  // 取第一个匹配的（如果有多个）
                            .orElse(null);
                    if (material == null) {
                        continue;
                    }

                    jsonString += "{\n" +
                            "\"FMaterialId\":{\n" +
                            "\"FNumber\":\"" + item.getK3No() + "\"\n" + // 填充物料编号
                            "},\n" +
                            "\"FUnitID\":{\n" +
                            "\"FNumber\":\"" + material.getBaseUnit() + "\"\n" + // 单位
                            "},\n" +
                            "\"FQty\":" + item.getTotal() + ",\n" + // 数量
                            "\"FBaseUnitId\":{\n" +
                            "\"FNumber\":\"" + material.getBaseUnit() + "\"\n" + // 单位
                            "},\n" +
                            "\"FStockId\":{\n" +
                            "\"FNumber\":\"" + item.getFSTOCKID() + "\"\n" + // 写死
                            "},\n" +
                            // Add FLot conditionally
                            (item.getFLot() != null && !item.getFLot().isEmpty() && !item.getFLot().equals("0") ?
                                    "        \"FLot\": {\n" +
                                            "          \"FNumber\": \"" + item.getFLot() + "\"\n" +
                                            "        },\n" : "") +
                            "        \"FStockStatusId\": {\n" +
                            "          \"FNumber\": \"" + item.getFSTOCKSTATUSID() + "\"\n" +
                            "        },\n" +

                            "\"FKeeperTypeId\":\"BD_KeeperOrg\",\n" +
                            "\"FOwnerId\":{\n" +
                            "\"FNumber\":\"128\"\n" + // 写死
                            "},\n" +
                            "\"FKeeperId\":{\n" +
                            "\"FNumber\":\"128\"\n" + // 写死
                            "},\n" +
                            "\"FFinUnit\":{\n" +
                            "\"FNumber\":\"" + material.getBaseUnit() + "\"\n" + // 单位
                            "}\n";

                    if (item.getFISKFPERIOD() != null && item.getFISKFPERIOD() == 1) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        // 格式化 FEXPIRYDATE 和 FPRODUCEDATE
                        String formattedExpiryDate = item.getFEXPIRYDATE() != null ? sdf.format(item.getFEXPIRYDATE()) : null;
                        String formattedProduceDate = item.getFPRODUCEDATE() != null ? sdf.format(item.getFPRODUCEDATE()) : null;

                        jsonString +=
                                "        ,\"FExpiryDate\": \"" + formattedExpiryDate + "\",\n" + // 格式化后的过期日期
                                        "        \"FProduceDate\": \"" + formattedProduceDate + "\"\n";
                    }

                    // 如果不是最后一个元素，添加逗号
                    if (i < items.size() - 1) {
                        jsonString += "},\n";
                    } else {
                        jsonString += "}\n";
                    }
                }

// 最终的 JSON 字符串


// 结束 FEntity 和 Model 部分
                jsonString += "]\n";
                jsonString += "}\n";
                jsonString += "}";


                log.info("金蝶其他出库单请求体:" + jsonString);
                String sResult = client.save("STK_MisDelivery", jsonString);
                log.info("金蝶其他出库单回调结果:" + sResult);
//            MessageUtil.sentMessage("25313",sResult, "金蝶回调结果");


                try {
                    // 使用Hutool的JSON工具解析
                    JSONObject jsonObject = JSONUtil.parseObj(sResult);

                    // 检查是否成功
                    boolean isSuccess = jsonObject.getByPath("Result.ResponseStatus.IsSuccess", Boolean.class);
                    if (isSuccess) {
                        // 提取Number字段
                        String number = jsonObject.getByPath("Result.ResponseStatus.SuccessEntitys[0].Number", String.class);

                        if (StringUtils.isNotBlank(number)) {
                            System.out.println("金蝶单号: " + number);

                            issuance.setStatus(2);
                            issuance.setUpdateTime(new Date());
                            issuance.setUpdateBy(person);
                            issuance.setReceiptNumber(number);
                            issuanceMapper.updateById(issuance);

                            String requisitionNo = issuance.getRequisitionNo();

                            Map<String, Object> requisitionmap = new HashMap<>();
                            requisitionmap.put("no", requisitionNo);


                            List<Requisition> requisitions = requisitionMapper.selectByMap(requisitionmap);
                            if (requisitions != null && requisitions.size() > 0) {
                                Requisition requisition = requisitions.get(0);
                                requisition.setStatus(2);
                                requisitionMapper.updateById(requisition);
                            }
                            log.info("即将插入记录:" + records);
                            //进行记录
                            for (LastRecord record : records) {
                                pcbOutMapper.insertRecord(record);
                            }


                            log.info("即将插入月用量:" + monthUseList);
                            pcbOutMapper.issuanceInsertList(monthUseList);


                        }
                    } else {
                        MessageUtil.sentMessage("25313", sResult, "金蝶回调结果失败");
                        System.out.println("Response status is not successful.");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("An error occurred while parsing the response.");
                }


            }


        }


    }


    @Override
    public void deleteAll() {

        QueryWrapper wrapper = new QueryWrapper();
        requisitionMapper.delete(wrapper);
        issuanceMapper.delete(wrapper);
        calculateItemMapper.delete(wrapper);


    }


    @Override
    public AddTo get(Long id) {
        AddTo result = new AddTo();

        Requisition requisition = requisitionMapper.selectById(id);
        if (requisition == null) {
            return null;
        }

        result.setNo(requisition.getNo());
        result.setType(requisition.getType());
        result.setWorkShopId(requisition.getWorkShopId());
        result.setRemark(requisition.getRemark());
        Map<String, Object> map1 = new HashMap<>();
        map1.put("application_id", id);
        map1.put("system_type", 1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("application_id", id);
        map2.put("system_type", 2);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("application_id", id);
        map3.put("system_type", 3);

        if (requisition.getType() == 1) {

            // 从 map1 中查询的 calculateItems
            List<CalculateItem> calculateItems = calculateItemMapper.selectByMap(map1);
            result.setNos(calculateItems);

// 从 map3 中查询的 calculateItems
            calculateItems = calculateItemMapper.selectByMap(map3);

// 同时设置 setCalculateList
            result.setCalculateList(calculateItems);


        } else if (requisition.getType() == 2) {

            List<CalculateItem> calculateItems = calculateItemMapper.selectByMap(map2);

// 提前检查calculateItems是否为空，避免不必要的操作
            if (!calculateItems.isEmpty()) {
                List<String> k3Nos = calculateItems.stream()
                        .map(CalculateItem::getK3No)
                        .collect(Collectors.toList());

                // 并行获取两个数据源，减少等待时间
                List<LastRecord> materialRecords = pcbOutMapper.getMaterialRecordsByK3Nos(k3Nos, requisition.getWorkShopId());
                List<MaterialDetail> minByK3Nos = stockMapper.findMinByK3Nos(k3Nos);

                // 使用toMap时添加合并函数避免重复key导致的异常
                Map<String, LastRecord> materialRecordMap = materialRecords.stream()
                        .collect(Collectors.toMap(LastRecord::getNo, Function.identity(), (existing, replacement) -> existing));

                Map<String, MaterialDetail> minMap = minByK3Nos.stream()
                        .collect(Collectors.toMap(MaterialDetail::get物料编码, Function.identity(), (existing, replacement) -> existing));

                // 使用forEach简化循环
                calculateItems.forEach(item -> {
                    Optional.ofNullable(materialRecordMap.get(item.getK3No()))
                            .ifPresent(record -> {
                                item.set物料记录日期(record.getDate());
                                item.set物料记录编号(record.getNumber());
                            });

                    Optional.ofNullable(minMap.get(item.getK3No()))
                            .ifPresent(detail -> item.set最小发料批量(detail.get最小发料批量()));
                });
            }


            List<AddTo.MaterialUItem> items = new java.util.ArrayList<>();

            for (CalculateItem tem : calculateItems) {
                AddTo.MaterialUItem item = new AddTo.MaterialUItem();
                item.set基本单位(tem.getUnit());
                item.set规格型号(tem.getType());
                item.set物料名称(tem.getName());
                item.set物料编码(tem.getK3No());
                item.setNum((int) tem.getTotal());
                item.setRemark(tem.getRemark());
                item.setNum((int) tem.getTotal());
                item.setBalance(tem.getBalance());

                item.set物料记录日期(tem.get物料记录日期());
                item.set物料记录编号(tem.get物料记录编号());
                item.set最小发料批量(tem.get最小发料批量());
                items.add(item);
            }
            result.setNo2list(items);

        }


        return result;
    }


    @Override
    public void uploadWorkshop(ExcelTO excelTo) {
        if (excelTo.getExcel() != null) {
            List<WorkShopExcelTO> excel = excelTo.getExcel();

            //删除操作
            QueryWrapper wrapper = new QueryWrapper();
            userWorkShopMapper.delete(wrapper);

            // 获取所有工作车间数据
            List<K3WorkShop> workShops = pcbOutMapper.getWorkShops();

            // 将 K3WorkShop 按部门名称映射成一个 Map<String, String>，键是部门名称，值是 rkey
            Map<String, String> departmentToRkeyMap = workShops.stream()
                    .collect(Collectors.toMap(
                            workshop -> workshop.get部门名称().replaceAll("\\s+", ""),  // 去掉部门名称的所有空格
                            K3WorkShop::getRkey,
                            (existing, replacement) -> existing // 忽略重复的键，保留第一个出现的值
                    ));

// 使用流遍历 Excel 数据，根据部门名称（四级部门）补充 rkey
            excel.stream().forEach(workShopExcel -> {
                String deptName = workShopExcel.get四级部门();
                if (deptName != null) {
                    // 去除 Excel 中部门名称的所有空格后再进行匹配
                    String deptNameWithoutSpaces = deptName.replaceAll("\\s+", "");
                    String rkey = departmentToRkeyMap.get(deptNameWithoutSpaces);
                    if (rkey != null) {
                        workShopExcel.setRkey(rkey);
                    }
                }
            });


            System.out.println(excel);

            List<UserWorkShop> collect = excel.stream()
                    .map(to -> {
                        // Skip if 工号 is null
                        if (to.get工号() == null) {
                            return null;
                        }

                        UserWorkShop userWorkShop = new UserWorkShop();
                        userWorkShop.setWorkshopName(to.get四级部门());  // 映射四级部门到workshopName
                        userWorkShop.setUserName(to.get姓名());        // 映射姓名到userName

                        // Ensure 工号 is a 5-digit string, padding with zeros if necessary
                        String userCode = String.format("%05d", to.get工号());
                        userWorkShop.setUserCode(userCode);            // 映射工号到userCode

                        // Ensure rkey is correctly parsed as Integer
                        userWorkShop.setWorkshopCode(to.getRkey());  // 映射rkey到workshopCode

                        return userWorkShop;
                    })
                    .filter(Objects::nonNull)  // Filter out null results from skipped entries
                    .collect(Collectors.toList());


            userWorkShopMapper.insertBatch(collect);


        }
    }

    @Override
    public void test() {
        Wrapper<CalculateItem> queryWrapper = new QueryWrapper<CalculateItem>()
                .isNotNull("batch_number").isNull("custcode");

        List<CalculateItem> calculateItems = calculateItemMapper.selectList(queryWrapper);
        for (CalculateItem items : calculateItems) {


            items.setCustcode(stockMapper.findCustCode(items.getBatchNumber()));
            calculateItemMapper.updateById(items);

        }


        log.info("结束");

    }


    @Override
    public void exportEasyExcel(HttpServletResponse response, String inputNo, String k3Name, String startTime, String endTime) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("发料记录导出" + DateUtil.format(new Date(), "yyyyMMdd"), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询数据
        List<ExportVO> dataList = exportMapper.queryExportData(inputNo, k3Name, startTime, endTime);

        // 导出Excel
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ExportVO.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("发料记录").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }
}
